package com.neusoft.neuiotms.dcam.fixed.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.bizcore.web.utils.EasyPoiExcelUtil;
import com.neusoft.bizcore.web.utils.EasyPoiStylerColorImpl;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.converter.GoodsFileConverter;
import com.neusoft.neuiotms.dcam.fixed.dto.GoodsFileDTO;
import com.neusoft.neuiotms.dcam.fixed.model.GoodsFile;
import com.neusoft.neuiotms.dcam.fixed.model.SpareType;
import com.neusoft.neuiotms.dcam.fixed.repository.GoodsFileRepository;
import com.neusoft.neuiotms.dcam.fixed.repository.SpareTypeRepository;
import com.neusoft.neuiotms.dcam.fixed.service.GoodsFileService;
import com.neusoft.neuiotms.dcam.fixed.vo.GoodsFileImportVO;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class GoodsFileServiceImpl implements GoodsFileService {

    @Autowired
    private GoodsFileConverter goodsFileConverter;
    @Autowired
    private GoodsFileRepository goodsFileRepository;
    @Autowired
    private SpareTypeRepository spareTypeRepository;

    @Override
    public GoodsFileDTO create(final GoodsFileDTO dto) {
        final GoodsFile model = this.goodsFileConverter.toModel(dto);
        this.goodsFileRepository.save(model);
        return this.goodsFileConverter.toDTO(model);
    }

    @Override
    public void delete(final Long id) {
        try {
            this.goodsFileRepository.deleteById(id);
        } catch (final Exception e) {
            throw new UnitedException("已经生成业务数据不能被删除！");
        }
    }

    @Override
    public GoodsFileDTO update(final Long id, final GoodsFileDTO dto) {
        GoodsFile model;
        try {
            model = this.goodsFileRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        dto.setId(model.getId());
        model = this.goodsFileConverter.toModel(dto);
        this.goodsFileRepository.save(model);

        return this.goodsFileConverter.toDTO(model);
    }

    @Override
    public List<GoodsFileDTO> findAll() {
        final List<GoodsFile> models = this.goodsFileRepository.findAll();
        return this.goodsFileConverter.toListDTO(models);
    }

    @Override
    public GoodsFileDTO details(final Long id) {
        final GoodsFile model;
        try {
            model = this.goodsFileRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }
        return this.goodsFileConverter.toDTO(model);
    }

    @Override
    public Page<GoodsFileDTO> search(final Pageable pageable, final Searchable searchable) {
        final Page<GoodsFile> result = this.goodsFileRepository.search(pageable, searchable);
        return this.goodsFileConverter.toPageDTO(result);
    }

    @Override
    public List<GoodsFileDTO> findBySpareType(final SpareType sparetype) {
        final List<GoodsFile> models = this.goodsFileRepository.findBySpareType(sparetype);
        return this.goodsFileConverter.toListDTO(models);
    }

    @Override
    public Workbook template() {
        final List<GoodsFileImportVO> list = new ArrayList<>();
        final Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("货品导入模板", "货品导入模板", ExcelType.XSSF),
                GoodsFileImportVO.class, list);

        //资产类型候选
        final List<SpareType> allTypes = this.spareTypeRepository.findAll();
        final List<String> typeConstraint = new ArrayList<>();
        allTypes.stream().forEach(l -> {
            typeConstraint.add(l.getName() + DCAMConsts.DICTIONARY_SPLITOR + l.getCode());
        });

        final Iterator<Sheet> iterator = workbook.iterator();
        while (iterator.hasNext()) {
            final Sheet sheet = iterator.next();
            //类型列加下拉候选框
            EasyPoiExcelUtil.sheetConstraintXSSF(sheet, DCAMConsts.ASSET_START_CONSTRAINT_ROW,
                    DCAMConsts.ASSET_CONSTRAINT_ROW, 1, 1, typeConstraint);

        }
        return workbook;
    }

    @Override
    public String upload(final MultipartFile file) {
        final StringBuilder errorMsg = new StringBuilder();
        final ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        params.setNeedVerify(true);
        try {
            final ExcelImportResult<GoodsFileImportVO> result =
                    ExcelImportUtil.importExcelMore(file.getInputStream(), GoodsFileImportVO.class, params);
            if (result.isVerifyFail()) {
                final List<GoodsFileImportVO> failList = result.getFailList();
                failList.forEach(l -> {
                    errorMsg.append("第" + (l.getRowNum() + 1) + "行," + l.getErrorMsg() + "! \n");
                });

            }
            final List<GoodsFile> models = new ArrayList<>();
            final List<GoodsFileImportVO> saveList = result.getList();
            for (final GoodsFileImportVO entity : saveList) {
                final GoodsFile model = this.goodsFileConverter.toModel(entity);
                //类型
                if (!StringUtils.isEmpty(entity.getSpareTypeName())
                        && entity.getSpareTypeName().contains(DCAMConsts.DICTIONARY_SPLITOR)) {
                    final String[] types = entity.getSpareTypeName().split(DCAMConsts.DICTIONARY_SPLITOR);
                    try {
                        final SpareType type = this.spareTypeRepository.findByCode(types[1]);
                        model.setSpareType(type);
                    } catch (final EntityNotFoundException e) {
                        throw new UnitedException("备品备件类型不存在", new Object[] {types[1] });
                    }
                }
                models.add(model);
            }
            if (!models.isEmpty()) {
                this.goodsFileRepository.saveAll(models);
            }

        } catch (final Exception e) {
            e.printStackTrace();
            GoodsFileServiceImpl.log.error("上传失败", e);
            throw new UnitedException(e.getMessage(), new Object[] {});
        }

        return errorMsg.toString();
    }

    @Override
    public Workbook export(final Searchable searchable, final Pageable pageable) {
        final Page<GoodsFile> models = this.goodsFileRepository.search(pageable, searchable);
        final List<GoodsFileImportVO> list = new ArrayList<>(models.getSize() == 0 ? 1 : models.getSize());
        models.forEach(model -> {
            list.add(this.goodsFileConverter.toVO(model));
        });
        final ExportParams param = new ExportParams("货品导出", "货品导出", ExcelType.XSSF);
        param.setStyle(EasyPoiStylerColorImpl.class);

        return ExcelExportUtil.exportExcel(param, GoodsFileImportVO.class, list);
    }

    @Override
    public List<GoodsFileDTO> listBySpareTypeCode(final String code) {
        final SpareType spareType = this.spareTypeRepository.findByCode(code);
        if (spareType != null) {
            final List<GoodsFile> models = this.goodsFileRepository.findBySpareType(spareType);
            return this.goodsFileConverter.toListDTO(models);
        }
        return null;
    }

}
